import requests
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, QMenu, QTreeWidgetItemIterator, QDialog, \
    QLabel, QCheckBox, QHBoxLayout, QPushButton, QMessageBox, QSplitter

from model.pulsar_cluster import PulsarCluster
from service.cluster_manager_service import ClusterManageService
from service.pulsar_tenant_service import TenantManageService
from ui.edit_dilog import EditDialog
from ui.tenant_tree import TenantTree


class SideBar(QWidget):
    def __init__(self, parent):
        super().__init__()
        self.cluster_service = ClusterManageService()
        self.cluster_service.on_cluster_changed = self.refresh_tree
        self.parent = parent
        self.tenant_tree = TenantTree(self.parent.main_content_area)
        self.tree = QTreeWidget()  # 提前初始化 self.tree
        self.initTree(self.cluster_service.cluster_list)
        self.tenant_dic = {}
        # self.tree.setMinimumHeight(100)

        self.tenant_tree.setHidden(True)
        self.splitter = QSplitter(Qt.Vertical)
        self.splitter.addWidget(self.tree)
        self.splitter.addWidget(self.tenant_tree)
        self.splitter.setStretchFactor(1, 1)

        layout = QVBoxLayout(self)
        layout.addWidget(self.splitter)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        self.setLayout(layout)

    def initTree(self, pulsar_clusters):
        self.tree.setHeaderHidden(True)
        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree.itemDoubleClicked.connect(self.refreshTenantTree)
        self.tree.customContextMenuRequested.connect(self.showContextMenu)  # 绑定上下文菜单

        # 设置样式表，使边框更窄
        self.tree.setStyleSheet("""
            QTreeWidget {
                border: none;
                padding: 0px;
            }
            QTreeWidget::item {
                padding: 0px;
            }
        """)

        # 添加树结构的项目
        for cluster in pulsar_clusters:
            root = QTreeWidgetItem(self.tree)
            root.setText(0, cluster.name)
            root.setText(1, str(cluster.id))
            root.setText(3, cluster.pulsar_addr)
            root.setText(4, cluster.admin_addr)
        self.tree.expandAll()  # 展开所有节点

    def showContextMenu(self, pos):
        # 获取鼠标的全局位置
        global_pos = QCursor.pos()
        # 将全局位置转换为相对于树控件的位置
        tree_pos = self.tree.mapFromGlobal(global_pos)
        # 获取树控件上的item
        item = self.tree.itemAt(tree_pos)
        menu = QMenu()
        new_action = menu.addAction("新增")

        if item is not None:
            edit_action = menu.addAction("编辑")
            delete_action = menu.addAction("删除")
        action = menu.exec_(global_pos)

        if action == new_action:
            # 新增节点
            dialog = EditDialog(self)
            if dialog.exec_():
                # 保存新节点信息
                name = dialog.name_edit.text()
                pulsar_addr = dialog.pulsar_addr_edit.text()
                admin_addr = dialog.admin_addr_edit.text()
                # 调用某个方法，传入name、pulsar_addr和admin_addr
                cluster = PulsarCluster(name=name, pulsar_addr=pulsar_addr, admin_addr=admin_addr)
                self.cluster_service.add(pulsar_cluster=cluster)

        elif item is not None and action == edit_action:
            # 编辑节点信息
            dialog = EditDialog(self, item.text(0), item.text(3), item.text(4), item.text(1))
            if dialog.exec_():
                # 保存编辑后的节点信息
                id = dialog.cluster_id
                name = dialog.name_edit.text()
                pulsar_addr = dialog.pulsar_addr_edit.text()
                admin_addr = dialog.admin_addr_edit.text()
                cluster = PulsarCluster(id=id, name=name, pulsar_addr=pulsar_addr, admin_addr=admin_addr)
                self.cluster_service.update(pulsar_cluster=cluster)

        elif item is not None and action == delete_action:
            self.delete_tenant(item)

    def delete_tenant(self, item):
        tenant_name = item.text(0)
        dialog = QDialog(self)
        dialog.setWindowTitle("删除租户")

        layout = QVBoxLayout()

        label = QLabel(f"确定要删除租户: {tenant_name} 吗？")
        layout.addWidget(label)

        self.force_delete_checkbox = QCheckBox("是否强制删除")
        layout.addWidget(self.force_delete_checkbox)

        button_layout = QHBoxLayout()

        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(dialog.reject)
        button_layout.addWidget(cancel_button)

        delete_button = QPushButton("确认")
        delete_button.setStyleSheet("background-color: red; color: white;")
        delete_button.clicked.connect(lambda: self.confirm_delete_tenant(dialog, tenant_name))
        button_layout.addWidget(delete_button)

        layout.addLayout(button_layout)
        dialog.setLayout(layout)

        dialog.exec_()

    def confirm_delete_tenant(self, dialog, tenant_name):
        force_delete = self.force_delete_checkbox.isChecked()
        url = self.cluster_service.cluster_list[0].admin_addr + "/admin/v2/tenants/" + str(tenant_name)
        headers = {'Content-Type': 'application/json'}
        params = {'force': str(force_delete).lower()}

        response = requests.delete(url, headers=headers, params=params)
        if response.status_code == 204:
            print(f"租户 {tenant_name} 删除成功")
            dialog.accept()
            self.refresh_tree()
        else:
            QMessageBox.warning(self, "删除失败", f"租户 {tenant_name} 删除失败，错误信息: {response.text}")

    def refresh_tree(self):
        # 清空树
        self.tree.clear()
        # 重新添加树结构的项目
        for cluster in self.cluster_service.cluster_list:
            print(cluster)
            root = QTreeWidgetItem(self.tree)
            root.setText(0, cluster.name)
            root.setText(1, str(cluster.id))
            root.setText(3, cluster.pulsar_addr)
            root.setText(4, cluster.admin_addr)
        self.tree.expandAll()  # 展开所有节点

    def refreshTenantTree(self):
        # 获取鼠标的全局位置
        global_pos = QCursor.pos()
        # 将全局位置转换为相对于树控件的位置
        tree_pos = self.tree.mapFromGlobal(global_pos)
        # 获取树控件上的item
        item = self.tree.itemAt(tree_pos)
        if item is not None:
            admin_url = item.text(4)
            tenant_service = self.tenant_dic.get(admin_url)
            if tenant_service is None:
                # 初始化
                cluster = PulsarCluster(item.text(1), item.text(0), item.text(3), item.text(4))
                tenant_service = TenantManageService(pulsar_cluster=cluster, parent=self.parent)
                self.tenant_dic[admin_url] = tenant_service

            # self.tenant_tree.tree.setMaximumWidth(200)  # 设置tenant_tree宽度
            self.tenant_tree.refresh(tenant_service)

        self.tenant_tree.setHidden(False)

    def printTree(self):
        iterator = QTreeWidgetItemIterator(self.tree)
        while iterator.value():
            current_item = iterator.value()
            print(current_item.text(0) + "  " + current_item.text(1))
            iterator += 1
